<?php
final class Kernel {
    private static $language;
    private static $langArray;
    private static $smarty;
    private static $mode;

    private function __construct() {}

    public static function init() {
        if (!Config::INSTALLED || isset($_SESSION['installer'])) {
            require dirname(__FILE__) . '/../install/Installer.php';
            Installer::init();
            return;
        }
        if (!is_writable(dirname(__FILE__) . '/../cache/smarty')) {
            throw new Exception("Cannot write to dir /cache/smarty");
        }
        date_default_timezone_set(Config::TIMEZONE);
        self::loadLanguage();
        
        require_once ROOT . '/libs/dibi/dibi.php';
        require_once ROOT . '/libs/persistence/Entity.php';
        require_once ROOT . '/libs/persistence/Persistence.php';
        Persistence::connect();
        
        if (isset($_GET['mode']) || isset($_POST['mode'])) {
            if ((isset($_GET['mode']) && ($_GET['mode'] == 'event')) ||
                    (isset($_POST['mode']) && ($_POST['mode'] == 'event'))) {
                self::initEvent();
                return;
            }
            if (isset($_GET['mode']) && ($_GET['mode'] == 'admin')) {
                self::initAdmin();
                return;
            }
        }
        self::initPublic();
    }

    public static function lang($key) {
        if (isset(self::$langArray[$key])) {
            return self::$langArray[$key];
        }
        return $key;
    }

    private static function initPublic() {
        self::$mode = 'PUBLIC';
        self::initSmarty();
        require ROOT . '/libs/PublicUI.php';
        PublicUI::init(self::$smarty);
        self::$smarty->assign(self::$langArray);
        self::$smarty->display('public/page.tpl');
    }

    private static function initAdmin() {
        if (!is_writable(ROOT . '/files')) {
            throw new Exception('Cannot write to folder files');
        }
        self::$mode = 'ADMIN';
        self::initSmarty();
        require ROOT . '/libs/Admin.php';
        Admin::init(self::$smarty);
        self::$smarty->assign(self::$langArray);
        self::$smarty->display('admin/page.tpl');
    }

    private static function initEvent() {
        self::$mode = 'EVENT';
        if (isset($_POST['inAdmin']) || isset($_GET['inAdmin'])) {
            require ROOT . '/libs/Admin.php';
            $redirect = Admin::event(isset($_POST['event']) ?
                    $_POST['event'] : $_GET['event']);
            header('Location: ' . WEB_DIR . '/admin/' . $redirect);
        } else {
            // probably no use, at least not so far
        }
    }

    private static function initSmarty() {
        require ROOT . '/libs/smarty/Smarty.class.php';
        self::$smarty = new Smarty();
        self::$smarty->template_dir = ROOT . '/templates';
        self::$smarty->compile_dir = ROOT . '/cache/smarty';
        self::$smarty->config_dir = ROOT . '/libs/smarty/configs';
        self::$smarty->plugins_dir = array(ROOT . '/libs/smarty/plugins');
        $config = array('webDir' => WEB_DIR, 'root' => ROOT,
                'timezone' => Config::TIMEZONE, 'language' => self::$language);
        self::$smarty->assign($config);
    }

    private static function loadLanguage() {
        self::$language = Config::LANGUAGE != '' ? Config::LANGUAGE :
                self::detectLanguage();
        $lang = parse_ini_file(ROOT . '/lang/' . self::$language . '.ini');
        self::$langArray = $lang;
    }

    private static function detectLanguage() {
        $language = self::chooseLanguage();
        if ($language == null) {
            $langs = glob(ROOT . '/lang/*.ini');
            if (!isset($langs[0])) {
                throw new Exception("No language files for installer!");
            }
            $langPart = substr($langs[0], strrpos($langs[0], '/') + 1);
            $language = substr($langPart, 0, strpos($langPart, '.'));
        }
        return $language;
    }

    private static function chooseLanguage() {
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach ($langs as &$lang) {
                $lang = explode(';', $lang);
                if (isset($lang[1])) {
                    $lang[1] = explode('=', $lang[1]);
                    $lang[1] = (float) $lang[1][1];
                } else {
                    $lang[1] = 1;
                }
            }
            while (count($langs) > 0) {
                $priority = 0;
                foreach ($langs as &$lang) {
                    if ($lang[1] > $priority) {
                        $priority = $lang[1];
                    }
                }
                for ($i = count($langs) - 1; $i >= 0; $i--) {
                    if ($langs[$i][1] == $priority) {
                        if (file_exists(ROOT . '/lang/' .
                                $langs[$i][0] . '.ini')) {
                            return $langs[$i][0];
                        }
                        array_splice($langs, $i, 1);
                    }
                }
            }
        }
        return null;
    }
}
?>
